package cn.gailvlun.gll.presentation.wish.drawer;

import android.app.Activity;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.github.markzhai.recyclerview.BaseViewAdapter;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;

import cn.gailvlun.gll.Constants;
import cn.gailvlun.gll.R;
import cn.gailvlun.gll.chatlib.db.ChatDB2;
import cn.gailvlun.gll.databinding.FragmentWishListBinding;
import cn.gailvlun.gll.net.HttpMethods;
import cn.gailvlun.gll.net.HttpSubscriber;
import cn.gailvlun.gll.net.ListRes;
import cn.gailvlun.gll.net.base.Profile;
import cn.gailvlun.gll.net.wish.OperationRecordReq;
import cn.gailvlun.gll.net.wish.Wish;
import cn.gailvlun.gll.net.wish.WishReq;
import cn.gailvlun.gll.presentation.base.BaseFragment;
import cn.gailvlun.gll.presentation.chat.ChatActivity;
import cn.gailvlun.gll.presentation.wish.WishType;
import cn.gailvlun.gll.util.DialogUtil;
import cn.gailvlun.gll.util.IsEmpty;
import cn.gailvlun.gll.util.RxUtil;
import io.reactivex.functions.Consumer;
import io.realm.Realm;
import rx_activity_result2.Result;



public class WishListFragment extends BaseFragment {

    private int mCurrentWishType;
    private WishReq req;

    public static WishListFragment getInstance(@WishType int wishType) {
        WishListFragment wishListFragment = new WishListFragment();
        Bundle bundle = new Bundle();
        bundle.putInt(Constants.EXTRA_WISH_TYPE, wishType);
        wishListFragment.setArguments(bundle);
        return wishListFragment;
    }

    private FragmentWishListBinding mBinding;
    private WishListAdapter mAdapter;
    private LinearLayoutManager mLayoutManager;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mCurrentWishType = getArguments().getInt(Constants.EXTRA_WISH_TYPE);
    }

    @Override
    protected View initComponent(@NonNull LayoutInflater inflater, @Nullable ViewGroup container) {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_wish_list, container, false);
        mAdapter = new WishListAdapter(mContext);
        mAdapter.setPresenter(new Presenter());
        mBinding.recyclerView.setAdapter(mAdapter);
        mLayoutManager = new LinearLayoutManager(mContext);
        mBinding.recyclerView.setLayoutManager(mLayoutManager);
        return mBinding.getRoot();
    }

    @Override
    protected void createHandler() {
        mBinding.srl.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                req.setLoadMore(true);
                getWishRecords(req);
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                req.setLoadMore(false);
                req.setId(0);
                getWishRecords(req);
            }
        });
    }

    @Override
    protected void loadData(@Nullable Bundle savedInstanceState) {
        req = new WishReq();
        if (mCurrentWishType == Constants.OWNER) {
            req.setType("owner");

        } else if (mCurrentWishType == Constants.ACCEPTER) {
            req.setType("accepter");
        }
        autoRefresh();
    }

    public void autoRefresh() {
        mBinding.srl.autoRefresh();
    }

    private void getWishRecords(final WishReq req) {
        HttpMethods.getWishService()
                .getWishRecords(req.getId(), req.getLimit(), req.getType(), req.getDirection())
                .compose(RxUtil.<ListRes<Wish>>applyScheduler())
                .compose(this.<ListRes<Wish>>bindToLifecycle())
                .subscribe(new HttpSubscriber<ListRes<Wish>>() {
                    @Override
                    protected void onSuccess(ListRes<Wish> response) {
                        mBinding.invalidateAll();
                        mBinding.srl.setEnableLoadmore(response.isNext());
                        if (response.getResults().size() > 0) {
                            int lastIndex = response.getResults().size() - 1;
                            req.setId(response.getResults().get(lastIndex).getId());
                        }

                        if (req.isLoadMore()) {

                            mAdapter.addAll(response.getResults(), WishListAdapter.Type.CONTENT.ordinal());
                        } else {
                            mBinding.invalidateAll();
                            mAdapter.clear();
                            if (IsEmpty.list(response.getResults())) {
                                mAdapter.add(null, WishListAdapter.Type.EMPTY.ordinal());

                            } else {
                                mAdapter.addAll(response.getResults(), WishListAdapter.Type.CONTENT.ordinal());
                            }
                        }

                        mBinding.srl.finishLoadmore(0);
                        mBinding.srl.finishRefresh(0);

                    }

                    @Override
                    protected void onFailure(String errMsg, @Nullable ListRes<Wish> response, int code) {
                        DialogUtil.showError(mContext, errMsg);
                        mBinding.srl.finishLoadmore(0);
                        mBinding.srl.finishRefresh(0);

                    }
                });
    }

    public class Presenter implements BaseViewAdapter.Presenter {
        public void onChatWith(int wishType, Wish wish) {
            Realm realm = Realm.getInstance(ChatDB2.INSTANCE.getConfiguration());
            realm.beginTransaction();

            Profile accepter = wish.getAccepter();
            Profile owner = wish.getOwner();
            if (wishType == Constants.OWNER) {
                realm.insertOrUpdate(accepter);
                ChatActivity.openActivity(mContext, "user:" + accepter.getId());
            } else if (wishType == Constants.ACCEPTER) {
                realm.insertOrUpdate(owner);
                ChatActivity.openActivity(mContext, "user:" + owner.getId());
            }

            realm.commitTransaction();
            realm.close();
        }

        public void displayDetail(Wish item) {
            WishDetailActivity.openActivity((Activity) mContext, item, mCurrentWishType, new Consumer<Result<Activity>>() {
                @Override
                public void accept(Result<Activity> activityResult) throws Exception {
                    autoRefresh();
                }
            });
        }

        public void onRealized(Wish item) {
            OperationRecordReq req = new OperationRecordReq()
                    .setWish_id(item.getId())
                    .setAction("finish");
            HttpMethods.getWishService().realized(req)
                    .compose(RxUtil.<Wish>applyScheduler())
                    .compose(WishListFragment.this.<Wish>bindToLifecycle())
                    .subscribe(new HttpSubscriber<Wish>() {
                        @Override
                        protected void onSuccess(Wish response) {

                            autoRefresh();

                        }

                        @Override
                        protected void onFailure(String errMsg, @Nullable Wish response, int code) {
                            DialogUtil.showError(mContext, errMsg);
                        }
                    });
        }


        public void onPostComment(int wishType, Wish item) {
            if (wishType == mCurrentWishType) {
                CommentActivity.openActivity((Activity) mContext, wishType, item.getId(), new Consumer<Result<Activity>>() {
                    @Override
                    public void accept(Result<Activity> activityResult) throws Exception {
                        autoRefresh();

                    }
                });
            }
        }

        public void onReviewComment(int wishType, Wish item) {
            CommentDetailActivity.openActivity(mContext, item);
        }


        public int getRealizingVisibility(int type, Wish item) {
            
            if (type == mCurrentWishType && item.getStatus() == 2) {
                return View.VISIBLE;
            } else {
                return View.GONE;
            }

        }

        public int getRealizedVisibility(int type, Wish item) {
            
            if (type == mCurrentWishType && item.getStatus() == 3) {
                return View.VISIBLE;
            } else {

                return View.GONE;
            }
        }
    }

}
